using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

using CStock;
using CUtil;


namespace CTrading
{
	/// <summary>
	/// Summary description for DialogTradeSystem.
	/// </summary>
	public class DialogTradeSystem : System.Windows.Forms.Form
	{
		private System.Windows.Forms.MainMenu mainMenu1;
		private EForms.MenuItem menu1;
		private EForms.MenuItem menuNew;
		private EForms.MenuItem menuSave;
		private EForms.MenuItem menuSaveAs;
		private EForms.MenuItem menuNewTradeCondition;
		


		private System.Collections.ArrayList tradeConditions;
		private System.Collections.ArrayList tradeConditionsUserControls;
		private CaptionTradeSystem tradeCaptionTradeSystem;
		private ITradeSystem tradeSystem ;
		private EForms.MenuItem menuOpenFile;
		private EForms.MenuItem menuRemoveLastTradeCondition;

		private IProgramContext programContext;
		private EForms.EButton buttonCancel;
        private EForms.EButton buttonOK;
        private IContainer components;

		public DialogTradeSystem(IProgramContext myProgramContext)
		{
			this.programContext = myProgramContext;
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
		
			tradeConditions = new System.Collections.ArrayList();
			tradeConditionsUserControls = new System.Collections.ArrayList();

            if (myProgramContext.TradeEconomy.TradeSimulation.TradeSystem  == null)
            {
                myProgramContext.TradeEconomy.TradeSimulation.TradeSystem = new TradeSystem();
                myProgramContext.TradeEconomy.TradeSimulation.TradeSystem.ID = "TestJunk";
                myProgramContext.TradeEconomy.TradeSimulation.TradeSystem.Serialize();
            }
            Debug.Assert(myProgramContext.TradeEconomy.TradeSimulation.TradeSystem != null, " No trade system file specified (or file deleted) - please create a Trade.xml file in the TradeSystem directory");

            this.tradeSystem = myProgramContext.TradeEconomy.TradeSimulation.TradeSystem;
            this.TradeSystemName = ((TradeSystem)(myProgramContext.TradeEconomy.TradeSimulation.TradeSystem)).Name;

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
				if(tradeConditionsUserControls != null && tradeConditionsUserControls.Count >0)
				{
					foreach(ConditionTradeSystem tcc in tradeConditionsUserControls)
					{
						tcc.ConditionChanged -= new ConditionChangedEventHandler(TradeConditionChanded);
					
					}
					//TradeConditionsUserControl tcc = tradeConditionsUserControls[i] as TradeConditionsUserControl ;

				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
            this.menu1 = new EForms.MenuItem();
            this.menuNew = new EForms.MenuItem();
            this.menuOpenFile = new EForms.MenuItem();
            this.menuSave = new EForms.MenuItem();
            this.menuSaveAs = new EForms.MenuItem();
            this.menuNewTradeCondition = new EForms.MenuItem();
            this.menuRemoveLastTradeCondition = new EForms.MenuItem();
            this.buttonCancel = new EForms.EButton();
            this.buttonOK = new EForms.EButton();
            this.tradeCaptionTradeSystem = new CTrading.CaptionTradeSystem();
            this.SuspendLayout();
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menu1});
            // 
            // menu1
            // 
            this.menu1.Icon = null;
            this.menu1.Index = 0;
            this.menu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuNew,
            this.menuOpenFile,
            this.menuSave,
            this.menuSaveAs,
            this.menuNewTradeCondition,
            this.menuRemoveLastTradeCondition});
            this.menu1.OwnerDraw = true;
            this.menu1.ShortcutText = "";
            this.menu1.Text = "Trade System";
            // 
            // menuNew
            // 
            this.menuNew.Icon = null;
            this.menuNew.Index = 0;
            this.menuNew.OwnerDraw = true;
            this.menuNew.ShortcutText = "";
            this.menuNew.Text = "New Trade System";
            this.menuNew.Click += new System.EventHandler(this.menuNew_Click);
            // 
            // menuOpenFile
            // 
            this.menuOpenFile.Icon = null;
            this.menuOpenFile.Index = 1;
            this.menuOpenFile.OwnerDraw = true;
            this.menuOpenFile.ShortcutText = "";
            this.menuOpenFile.Text = "Open File";
            this.menuOpenFile.Click += new System.EventHandler(this.menuOpenFile_Click);
            // 
            // menuSave
            // 
            this.menuSave.Icon = null;
            this.menuSave.Index = 2;
            this.menuSave.OwnerDraw = true;
            this.menuSave.ShortcutText = "";
            this.menuSave.Text = "Save";
            this.menuSave.Click += new System.EventHandler(this.menuSave_Click);
            // 
            // menuSaveAs
            // 
            this.menuSaveAs.Icon = null;
            this.menuSaveAs.Index = 3;
            this.menuSaveAs.OwnerDraw = true;
            this.menuSaveAs.ShortcutText = "";
            this.menuSaveAs.Text = "Save As";
            this.menuSaveAs.Click += new System.EventHandler(this.menuSaveAs_Click);
            // 
            // menuNewTradeCondition
            // 
            this.menuNewTradeCondition.Icon = null;
            this.menuNewTradeCondition.Index = 4;
            this.menuNewTradeCondition.OwnerDraw = true;
            this.menuNewTradeCondition.ShortcutText = "";
            this.menuNewTradeCondition.Text = "Add Trade Condition";
            this.menuNewTradeCondition.Click += new System.EventHandler(this.menuNewTradeCondition_Click);
            // 
            // menuRemoveLastTradeCondition
            // 
            this.menuRemoveLastTradeCondition.Icon = null;
            this.menuRemoveLastTradeCondition.Index = 5;
            this.menuRemoveLastTradeCondition.OwnerDraw = true;
            this.menuRemoveLastTradeCondition.ShortcutText = "";
            this.menuRemoveLastTradeCondition.Text = "Remove Last Trade Condition";
            this.menuRemoveLastTradeCondition.Click += new System.EventHandler(this.menuRemoveLastTradeCondition_Click);
            // 
            // buttonCancel
            // 
            this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.buttonCancel.Location = new System.Drawing.Point(480, 368);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(128, 24);
            this.buttonCancel.TabIndex = 4;
            this.buttonCancel.Text = "Cancel";
            this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
            // 
            // buttonOK
            // 
            this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.buttonOK.Location = new System.Drawing.Point(240, 368);
            this.buttonOK.Name = "buttonOK";
            this.buttonOK.Size = new System.Drawing.Size(104, 24);
            this.buttonOK.TabIndex = 3;
            this.buttonOK.Text = "OK";
            this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
            // 
            // tradeCaptionTradeSystem
            // 
            this.tradeCaptionTradeSystem.Location = new System.Drawing.Point(0, 0);
            this.tradeCaptionTradeSystem.Name = "tradeCaptionTradeSystem";
            this.tradeCaptionTradeSystem.Size = new System.Drawing.Size(1008, 40);
            this.tradeCaptionTradeSystem.TabIndex = 0;
            // 
            // DialogTradeSystem
            // 
            this.AcceptButton = this.buttonOK;
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.CancelButton = this.buttonCancel;
            this.ClientSize = new System.Drawing.Size(1008, 416);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.buttonOK);
            this.Controls.Add(this.tradeCaptionTradeSystem);
            this.Menu = this.mainMenu1;
            this.Name = "DialogTradeSystem";
            this.Text = "Trade System ";
            this.ResumeLayout(false);

		}
		#endregion


		/// <summary>
		/// here I supply the method for changing the trade conditions
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void TradeConditionChanded( object sender , ConditionChangedEvent e )
		{
			int i = e.Index;
			TradeCondition tc = e.Condition as TradeCondition;

		}
		/// <summary>
		/// the method for a new trade system
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuNew_Click(object sender, System.EventArgs e)
		{
			CreateDefaultTradeSystem();
		}
		private void CreateDefaultTradeSystem()
		{
			RemoveAllConditionTradeSystems();

			this.Cursor = System.Windows.Forms.Cursors.WaitCursor;

			tradeSystem = new TradeSystem();
			object o = new Object();

			
			this.Cursor = System.Windows.Forms.Cursors.Default;
			this.Text = "Trade System : " + tradeSystem.FileName;

		}

	
	
		private void menuNewTradeCondition_Click(object sender, System.EventArgs e)
		{			
			if(tradeSystem == null)
				tradeSystem = new TradeSystem();
			TradeCondition MytradeCon = new TradeCondition();
			AddTradeConditionTradeSystem(MytradeCon);		
		
		}
		private void AddTradeConditionTradeSystem(TradeCondition MytradeCon)
		{
			ConditionTradeSystem Mytcc = null;
			

			if(tradeConditionsUserControls.Count <1)
			{
				Mytcc = new ConditionTradeSystem(0,MytradeCon);
				Mytcc.Left = this.ClientRectangle.Left +10;
				Mytcc.Top = this.ClientRectangle.Top +50;
			}
			else
			{
				Mytcc = new ConditionTradeSystem(tradeConditionsUserControls.Count,MytradeCon);
				ConditionTradeSystem tccPrevious = tradeConditionsUserControls[tradeConditionsUserControls.Count -1] as ConditionTradeSystem;
				
				Mytcc.Left = tccPrevious.Left ;
				Mytcc.Top = tccPrevious.Top +25;


			}

			Mytcc.ConditionChanged += new ConditionChangedEventHandler(TradeConditionChanded);
			tradeConditionsUserControls.Add(Mytcc);
			this.Controls.Add(Mytcc);

		}
		private void CreateTradeSystemFromUserControls()
		{
			tradeSystem.BuyConditions = new CStock.TradeCondition[0];
			tradeSystem.SellConditions = new CStock.TradeCondition[0];

			foreach(Control c in this.Controls)
			{
				ConditionTradeSystem cc = c as ConditionTradeSystem ;

				if(cc != null)
				{
					TradeCondition tc = cc.TradeCondition;
					if(tc.BuyOrSell == "Buy")
					{
						tradeSystem.AddBuyCondition(tc);
					}
					else
					{
						tradeSystem.AddSellCondition(tc);
					}
				}

			}

		}
		private void ShowConditionTradeSystemsFromTradeSystem()
		{

			tradeConditions = new System.Collections.ArrayList();
			tradeConditionsUserControls=new System.Collections.ArrayList();

			for(int i = 0; i < this.tradeSystem.BuyConditions.GetLength(0); i ++)
			{
				ITradeCondition MytradeCon = this.tradeSystem.BuyConditions[i];
				AddTradeConditionTradeSystem(MytradeCon as TradeCondition);		
			}
			for(int i = 0; i < this.tradeSystem.SellConditionsCollection.Count; i ++)
			{
				TradeCondition MytradeCon = this.tradeSystem.SellConditionsCollection[i] as TradeCondition;
				AddTradeConditionTradeSystem(MytradeCon);		
			}
			

		}
		private void SaveTradeSystem()
		{
			CreateTradeSystemFromUserControls();
			if(tradeSystem != null)
			{
				this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                tradeSystem.Serialize();
				//XMLSerializable.SerializeObject(tradeSystem,tradeSystem.FileName );			
				
				this.Cursor = System.Windows.Forms.Cursors.Default;
                // assign saved tradesystem in the trade simulation
                this.programContext.TradeEconomy.TradeSimulation.TradeSystem = tradeSystem;
			}
			else
			{
				MessageBox.Show("No trade system specified");
			}
			//this.Text = "Trade System : " + openFileDialog1.FileName;
			this.Text = "Trade System : " + tradeSystem.FileName;
		}
		private void menuSave_Click(object sender, System.EventArgs e)
		{
			
			 SaveTradeSystem();

		}

		private void menuOpenFile_Click(object sender, System.EventArgs e)
		{
			RemoveAllConditionTradeSystems();

			Stream myStream;
			OpenFileDialog openFileDialog1 = new OpenFileDialog();

			openFileDialog1.InitialDirectory = this.programContext.Configuration.Directories.ApplicationPath + "\\TradeSystems\\" ;
			openFileDialog1.Filter = "Trade System files (*.xml)|*.xml|All files (*.*)|*.*" ;
			openFileDialog1.FilterIndex = 1 ;
			openFileDialog1.RestoreDirectory = true ;

			if(openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				
				if((myStream = openFileDialog1.OpenFile())!= null)
				{
					object o = new TradeSystem();		
					XMLSerializable.DeSerializeObject( ref o, myStream);
					tradeSystem = o as TradeSystem;

					myStream.Close();
					this.Text = "Trade System : " + openFileDialog1.FileName;
					tradeSystem.SetIDFromLongFileName(openFileDialog1.FileName);
				}

				ShowConditionTradeSystemsFromTradeSystem();
			
			}
			
			

		}
	
		private void menuSaveAs_Click(object sender, System.EventArgs e)
		{
			CreateTradeSystemFromUserControls();
			if(tradeSystem != null)
			{
			
				Stream myStream ;
				SaveFileDialog saveFileDialog1 = new SaveFileDialog();

				saveFileDialog1.InitialDirectory = this.programContext.Configuration.Directories.TradeSystemsTemplatesPath;
				saveFileDialog1.Filter = "Trade System files (*.xml)|*.xml|All files (*.*)|*.*"  ;
				saveFileDialog1.FilterIndex = 1 ;
				saveFileDialog1.RestoreDirectory = true ;

				if(saveFileDialog1.ShowDialog() == DialogResult.OK)
				{
				

					if((myStream = saveFileDialog1.OpenFile()) != null)
					{
						this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
						
						this.Text = "Trade System : " + saveFileDialog1.FileName;
						//tradeSystem.FileName = saveFileDialog1.FileName;
						tradeSystem.SetIDFromLongFileName(saveFileDialog1.FileName);

						//new name:
						string[] arrStr = tradeSystem.FileName.Split(new Char[] {'\\'},100);
						string strNameBase = arrStr[arrStr.GetLength(0)-1];
						arrStr = strNameBase.Split(new Char[] {'.'},100);
						tradeSystem.ID = arrStr[0];

						object o = tradeSystem.BuyConditions;
						object b = tradeSystem.SellConditions;
						object v = ((TradeSystem)tradeSystem).TradeConditions;



						XMLSerializable.SerializeObject(tradeSystem,myStream);			
						this.Cursor = System.Windows.Forms.Cursors.Default;

						myStream.Close();
						
					}

				}
				
			}
		}
		private void menuRemoveLastTradeCondition_Click(object sender, System.EventArgs e)
		{
			ConditionTradeSystem cc = null;
			foreach(Control c in this.Controls)
			{
				cc = c as ConditionTradeSystem;

			}
			if(cc != null)
			{
				this.Controls.Remove(cc);
			}
		}
		private void RemoveAllConditionTradeSystems()
		{
			
			for(int i = this.Controls.Count -1; i > -1; i --)
			{
				ConditionTradeSystem cc = this.Controls[i] as ConditionTradeSystem;
				if(cc != null)
				{
					this.Controls.Remove(cc);
					cc.Dispose();
				}
				//cc = c as ConditionTradeSystem;
			}
			
		}

		private void buttonOK_Click(object sender, System.EventArgs e)
		{
            this.DialogResult = DialogResult.OK;
			SaveTradeSystem();
			this.Close();
		}

		private void buttonCancel_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}
		#region public properties

		public ITradeSystem TradeSystem 
		{
			get
			{
				return this.tradeSystem;
			}
			set
			{
				this.tradeSystem = value;
			}
			
		}
     
		public string TradeSystemName 
		{
			get
			{
				return this.tradeSystem.FileName;
			}
			set
			{
				try
				{
					string fileName = value;
					//this.Name = value;
					System.IO.FileStream fstream =null;
					fileName = this.programContext.Configuration.Directories.TradeSystemsTemplatesPath + "\\" + fileName + ".xml";
					if(!System.IO.File.Exists(fileName))
                    {
                        MessageBox.Show("TradeSystem not set correct : " + fileName + " - opening default dialog");
                        ShowConditionTradeSystemsFromTradeSystem();
                        return;
                    }
                    
                    fstream = new System.IO.FileStream(fileName,System.IO.FileMode.Open,System.IO.FileAccess.ReadWrite);
				
					if(fstream != null)
					{
						//string strFileName = openFileDialog1.FileName;
						object o = new TradeSystem();		
						XMLSerializable.DeSerializeObject( ref o,fstream);
						tradeSystem = o as TradeSystem;

						fstream.Close();
						this.Text = "Trade System : " + fileName;
						tradeSystem.SetIDFromLongFileName(fileName);
						
					}
					ShowConditionTradeSystemsFromTradeSystem();
				}
				catch(Exception exc)
				{
					Debug.Assert(false,"Error setting trade system name " + value.ToString(),exc.Message);
				}
			}
			
		}

		#endregion

	}
}
